package com.example.siyun.service.impl.loginserviceimpl;

import com.example.siyun.pojo.Userr;
import com.example.siyun.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: 全
 * @Date: 2022/10/2 19:27
 * @Description:
 */
@Component
public class CustomUserDetailsService implements UserDetailsService {



    @Autowired
    private UserServiceImpl userService;
    /**
     * 需新建配置类注册一个指定的加密方式Bean，或在下一步Security配置类中注册指定
     */
    @Autowired
    @Lazy
    private PasswordEncoder passwordEncoder;
    @Transactional
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过用户名从数据库获取用户信息
        Userr userr = userService.login(username);
        System.out.println(userr);
        if(userr!=null){
            WebUtils.getSession().setAttribute("usernamename",userr.getUsername());
            WebUtils.getSession().setAttribute("loginname",userr.getUsername());
            WebUtils.getSession().setAttribute("username",userr.getUsername());
            WebUtils.getSession().setAttribute("saltsalt",userr.getSalt());
            WebUtils.getSession().setAttribute("passwordpassword",userr.getPassword());
        }

//        if (userr == null) {
//            throw new UsernameNotFoundException("用户不存在");
//        }
        List<GrantedAuthority>authorities=new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_"+"aa"));
        return new User(
                userr.getUsername(),
                passwordEncoder.encode(userr.getPassword()),authorities
        );
    }
}
